import { defineStore, createPinia } from "pinia";
import { GlobalState } from "./interface";
import piniaPersistConfig from "@/config/piniaPersist";
import piniaPluginPersistedstate from "pinia-plugin-persistedstate";

// defineStore 调用后返回一个函数，调用该函数获得 Store 实体
export const GlobalStore = defineStore({
	// id: 必须的，在所有 Store 中唯一
	id: "GlobalState",
	// state: 返回对象的函数
	state: (): GlobalState => ({
		userInfo: {
			username: "",    //用户名
			user_id: "",     //用户id
			avatar: "",     //头像
			order_num:3000,  //消费订单数
			amount:1888888,  //消费总金额
			toBePaidNum:10,   //待付款数量
			pendingOrderNum:20,   //待接单数量
			inProductionNum:30,   //生产中数量
			goodsNum:40,   //待发货
		},
		affiche:true,  //公告是否显示
		token: ""  //空字符串为未登录  非空为已登录 
	}),
	getters: {
		is_login : state => state.token === "" ?  false : true,
		getAffiche : state => state.affiche
	},
	actions: {
		setUserInfo(userInfo: {
			username: string,
			user_id: string,
			avatar:string,
			order_num:number,
			amount:number,
			toBePaidNum: number;   //待付款数量
			pendingOrderNum: number;   //待接单数量
			inProductionNum: number;   //生产中数量
			goodsNum: number;   //待发货
		}, token: string) {
			this.userInfo.user_id = userInfo.user_id;
			this.userInfo.username = userInfo.username;
			this.userInfo.avatar = userInfo.avatar;
			this.userInfo.order_num = userInfo.order_num;
			this.userInfo.amount = userInfo.amount;
			this.token = token;
		},
		loginOut(){
			this.token = "";
		} ,
		setAffiche(bool:boolean){
            this.affiche = bool;
		}
	},
	persist: piniaPersistConfig("GlobalState")
});

// piniaPersist(持久化)
const pinia = createPinia();
pinia.use(piniaPluginPersistedstate);

export default pinia;
